package routers

import (
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"shang/conmon"
	"shang/controllers"
	"strconv"
)

func init() {
	beego.InsertFilter("/user/*", beego.BeforeRouter, filterFunc)
	beego.Router("/", &controllers.MainController{})
	beego.Router("/register", &controllers.RegController{}, "post:Reg")
	beego.Router("/login", &controllers.LoginController{}, "post:Login")
	beego.Router("/user/im", &controllers.ImController{}, "get:Im")
	beego.Router("/send", &controllers.SendController{}, "post:Send")
	beego.Router("/password", &controllers.UpController{}, "post:Password")

}

func filterFunc(ctx *context.Context) {
	token := ctx.Request.Header.Get("token")
	if token == "" {
		ctx.Output.JSON(map[string]interface{}{
			"code": 400,
			"msg":  "token不能为空",
		}, true, false)
	}

	payload, err := conmon.ParseToken(token)

	if err != nil {
		ctx.Output.JSON(map[string]interface{}{
			"code": 400,
			"msg":  err.Error(),
		}, true, false)
	}
	userid, _ := strconv.Atoi(payload)
	conmon.Userid = userid
}
